#include "StdAfx.h"

BackTester::BackTester(void) {}

BackTester::~BackTester(void) { }

void BackTester::StartTest(const vector<Quotation>& stockQuots, int begin, int end, TradeSystem *syst)
{
	this->_System = syst;
	bool posSell = true; 
	bool enableLong = true;
	bool enableShort = false;
	int sell, cover;
	
	for (int i = begin+1; i < end; i++)
	{
		if(posSell)
		{
			if(enableShort)
			{
				cover = this->_System->Cover(stockQuots[i], i);
				
				if (cover != 0) 
				{
					this->_Statistics.AddTrade(_COVER, this->_System->GetCoverPrice(), stockQuots[i]._DateTime);
					
					if (cover == -1) // cover por stop
						enableShort = false;

					enableLong = true;
				}
			}

			if(enableLong)
			{
				if ( this->_System->Buy(stockQuots[i], i) ) 
				{
					this->_Statistics.AddTrade(_BUY, this->_System->GetBuyPrice(), stockQuots[i]._DateTime);
					posSell = false;
					enableLong = true;
					enableShort = true;
				}
			}
		}
		else
		{
			if(enableLong)
			{
				sell = this->_System->Sell(stockQuots[i], i);
				 
				if (sell != 0) 
				{
					this->_Statistics.AddTrade(_SELL, this->_System->GetSellPrice(), stockQuots[i]._DateTime);
									
					if (sell == -1) //sell por stopGain
						enableLong = false;

					posSell = true;
					enableShort = true;
				}
			}

			if(enableShort)
			{
				if ( this->_System->Short(stockQuots[i], i) ) 
				{
					this->_Statistics.AddTrade(_SHORT, this->_System->GetShortPrice(), stockQuots[i]._DateTime);
					enableShort = enableLong = true;
				}
			}
		}		
	}
}
